const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

const APP_ID = 'ttbe1bc8a621136dd701';
const APP_SECRET = '0001068ac4773721f549cb6319eec8b87d179917';

// openid 路由
app.post('/getOpenId', async (req, res) => {
  const { code } = req.body;
  if (!code) {
    return res.status(400).json({ success: false, message: '缺少 code' });
  }
  try {
    const result = await axios.get('https://developer.toutiao.com/api/apps/jscode2session', {
      params: {
        appid: APP_ID,
        secret: APP_SECRET,
        code
      }
    });
    res.json({ success: true, openid: result.data.openid, data: result.data });
  } catch (e) {
    res.status(500).json({ success: false, message: '服务端异常', detail: e.message });
  }
});

// 支付回调接口
app.post('/callback', (req, res) => {
  console.log('收到支付回调:', req.body);
  res.send('ok');
});

// 测试根路径
app.get('/', (req, res) => {
  res.send('Hello Douyin Cloud!');
});

// 端口必须监听 8000（抖音云容器平台要求）
const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log('Server running on port', port);
});